package com.example.decoder;

import android.util.Log;

public class Convert {
	// 十六进制转二进制
	public static String HToB(String a) {
		String b = Integer.toBinaryString(Integer.valueOf(toD(a, 16)));
		return b;
	}

	// 二进制转十六进制
	public static String BToH(String a) {
		// 将二进制转为十进制再从十进制转为十六进制
		String b = Integer.toHexString(Integer.valueOf(toD(a, 2)));
		return b;
	}

	/**
	 * 返回的结果是xx&yy的样式， 其中xx是64进制表示，yy是10进制
	 * 比如961, 10, 返回的结果就是F1&10
	 * 比如GCP2E&648 就返回 
	 * @return
	 */
	public static String _10toAny(long dec, int anyEncoder, String XL) {
		String b64 = _10to64(dec, XL);
		return b64 + "&"+ anyEncoder;
	}
	
	/**
	 * 返回的结果是100&34,45,10的样式
	 * 比如F1&10 返回的结果就是10&9,6,1
	 * 比如GCP2E&648 就返回 
	 * @return
	 */
	public static String anyTo10d(String any, String XL) {
		String[] anys = any.split("&");
		if(anys.length != 2){
			return "";
		}
		int encode = Integer.parseInt(anys[1]);
		String b64 = anys[0];
		
		
	}
	
	// 任意进制数转为十进制数
	public static String toD(String a, int b) {
		int r = 0;
		for (int i = 0; i < a.length(); i++) {
			r = (int) (r + formatting(a.substring(i, i + 1))
					* Math.pow(b, a.length() - i - 1));
		}
		return String.valueOf(r);
	}

	// 将十六进制中的字母转为对应的数字
	private static int formatting(String a) {
		int i = 0;
		for (int u = 0; u < 10; u++) {
			if (a.equals(String.valueOf(u))) {
				i = u;
			}
		}
		if (a.equals("a")) {
			i = 10;
		}
		if (a.equals("b")) {
			i = 11;
		}
		if (a.equals("c")) {
			i = 12;
		}
		if (a.equals("d")) {
			i = 13;
		}
		if (a.equals("e")) {
			i = 14;
		}
		if (a.equals("f")) {
			i = 15;
		}
		return i;
	}

	public static String _10to16(long dec) {
		return Long.toHexString(dec);
	}

	private static char convert10_64char(long d, final char[] chs) {
		if (d > 63) {
			return '#';
		}
		return chs[(int) d];
	}

	private static int convert64_10int(char c, final char[] chs) {
		for (int i = 0; i < chs.length; i++) {
			if (chs[i] == c) {
				return i;
			}
		}
		return -1;
	}

	public static String _10to64(long d, String XL) {
		final char[] chs = XL.toCharArray();
		String ret = "";
		do {
			ret = "" + convert10_64char(d % 64, chs) + "" + ret;
			d = d / 64;
		} while (d > 0);

		return ret;
	}

	public static long _64to10(String base, String XL) {
		long ret = 0;
		char[] bs = base.toCharArray();
		char[] XLs = XL.toCharArray();
		for (int i = bs.length - 1; i >= 0; i--) {
			Math.pow(64, bs.length - i - 1);
			ret += convert64_10int(bs[i], XLs) * Math.pow(64, bs.length - i - 1);
			Log.i("allan", "bs[i] " + bs[i] + " " + ret);
		}

		return ret;
	}
	
	public static String _10to3(long dec) {
		String ret = "";
		do{
			ret = "" + dec%3 + ret;
			dec = dec/3;
		}while(dec>0);
		return ret;
	}
}
